//
//  UITextView+Emoticon.swift
//  表情键盘
//
//  Created by 吴婷婷 on 15/11/15.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
extension UITextView {
    ///图片表情完整字符串内容
    var emoticonText: String {
        let attrString = attributedText
        var strM = String()
        attrString.enumerateAttributesInRange(NSRange(location: 0, length: attrString.length), options: []) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.emoticon.chs ?? ""
            } else {
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
            
        }
        return strM
    }
    
    func insertEmoticon(em: Emoticon) {
        if em.isEmpty {
            return
        }
        if em.isRemoved {
            deleteBackward()
            return
        }
        if let emoji = em.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
        }
        
        insertImageEmoticon(em)
        
        // 5. 通知`代理`文本变化了 － textViewDidChange? 表示代理如果没有实现方法，就什么都不做，更安全
        delegate?.textViewDidChange?(self)
    }
    func insertImageEmoticon(em: Emoticon) {

        //1>创建图像附件
        let imageText = EmoticonAttachment(emoticon: em).imageText(font!)
        
        //2>获取textView的属性文本
        let textM = NSMutableAttributedString(attributedString: attributedText)
        
        textM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        //3>修改textView中的文本,解决光标问题
        let range = selectedRange
        attributedText = textM
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
        
    }
}

